package com.kiku.reggie.controller;

import com.kiku.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @className: CommonController
 * @description: TODO 类描述
 * @author: kiku
 * @date: 2023/10/21 20:28
 **/
//实现文件的上传和下载
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basepath;

    //实现文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //这里的file是一个临时文件，需要进行转存到指定的位置,否则在请求结束后会消失
        log.info(file.toString());
        //获得原始文件名
        String name = file.getOriginalFilename();
        //获得文件的后缀名
        String s = name.substring(name.lastIndexOf("."));
        //使用uuid进行文件名的生成，防止出现重名问题
        String uuidName = UUID.randomUUID().toString();
        //创建一个目录对象
        File dir = new File(basepath);
        //判断当前的目录是否存在
        if (!dir.exists()) {
            //进行目录的创建
            dir.mkdirs();
        }
        String filename = uuidName + s;
        file.transferTo(new File(basepath + filename));
        //返回文件名
        return R.success(filename);
    }

    //实现文件下载

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //使用输入流读取文件内容
        FileInputStream inputStream = new FileInputStream(new File(basepath + name));
        //使用输出流将文件写回浏览器，在浏览器进行图片的展示
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("imag/jpeg");
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, length);
            outputStream.flush();
        }
        inputStream.close();
        outputStream.close();

    }
}
